/*
 * TinyWiki index - v0.1.0
 *  Copyright 2010 - 2011, itozyun
 *  Released under the MIT, BSD, and GPL Licenses.
 */

	var wiki = {
		baseUrl: (function(){
			var ary = location.pathname.split( '\/');
			return ary[ ary.length -1];
		})(),
		blankWiki: function( id){
			return {
				id:				id || 'new_wiki_' +( new Date()).getTime(),
				pubdate:		'' +( new Date()).toLocaleString(),
				pageTotal:		0
			}
		},
		event: {
			WIKI_DELETE_EVENT:		'wikiDeleteEvent',
			SETTING_UPDATE_EVENT:	'settingUpdateEvent',
			SETTING_CLOSED_EVENT:	'settingClosedEvent'
		},
		updating: false
	};

// ---------------------------------------------------
// wiki list
//	
	wiki.list = function( h2Id, ulId, counterId){
		var	items = [];
		var	length = 0;
		var	header = $( '#' +h2Id);
		var	ul = $( '#' +ulId);
		var	counter = $( '#' +counterId);
		
		ul.bind( wiki.event.SETTING_UPDATE_EVENT, update);
		ul.bind( wiki.event.WIKI_DELETE_EVENT, onWikiDeleteHandler);

		ul.sortable( {
		    placeholder: 'wiki-thumb-placeholder',// placeholder に適用するCSSクラス(.は不要)
		    start: wiki.setting.hide,
		    update: update
		});

		function data(){
			var ret = [];
			ul.children( 'li').each( function( i, el){
				var id = $( this).attr( 'id');
				var i = getIndexById( id);
				if( i >= 0){
					ret.push( items[ i].data);
				}
			});
			return ret;
		}
		
		function updateCounter(){
			counter.text( length);
		}		
		function update(){
			header.addClass('ui-state-ajax');
			wiki.updating = true;
			osapi.appdata.update({ data: {list: data()} }).execute( function(response) {
				header.removeClass('ui-state-ajax');
				wiki.updating = false;
				
				if( response.error) {
					alert('__MSG_OOPS__' + '__MSG_HTTP_FORBIDDEN__');
					return false;
				}
				// wiki.social.sendMsg
			});					
		}

		function getIndexById( id){
			length = items.length;
			for( var i=0; i<length; ++i){
				if( items[ i].data.id === id){
					break;
				}
			}
			return ( length === i) ? -1 : i;
		}
		
		function onWikiDeleteHandler( e, id){
			var i = getIndexById( id);
			if( i >= 0){
				items[ i].remove();
				items.splice( i, 1);
				length--
				updateCounter();
				sortControl();
				update();							
			}
		}
		
		function sortControl(){
			if( length > 1){ // アイテムがひとつのときに不具合
				ul.sortable( 'enable');
			} else {
				ul.sortable( 'disable');
			}
		}
								
		return {
			add: function( data){
				var newItem = wiki.listItem.apply( {}, [ ul, data]);
				items.push( newItem);
				ul.append( newItem.el);
				
				length = items.length;
				updateCounter();
				sortControl();
			},
			create: function( data){
				this.add( data || wiki.blankWiki( 'new_wiki_' +( new Date()).getTime()));
				update();
			}					
		}
	};

// ---------------------------------------------------
// wiki list-item
//	
	wiki.listItem = function( list, data){
		var el = wikiThumbnailTemplate.clone();
		var editButton = el.find( '.wiki-edit').click( onEditClick);
		var settingButton = el.find( '.wiki-setting').click( onSettingClick);
		var deleteButton = el.find( '.wiki-delete').click( onDeleteClick);
		build();
		
		function build(){
			el.attr( 'id', data.id);
			
			if( data.isRocked){
				el.addClass( 'rocked');
			} else {
				el.removeClass( 'rocked');
			}
			if( data.color){
				$( '.wiki-color', el).removeClass().addClass( 'wiki-color').addClass( data.color);
			}
			if( data.title){
				$( 'h3>a', el).text( data.title);
			}
			if( data.id){
				$( 'h3>a', el).attr( 'href', wiki.baseUrl + '?view=wiki&wikiId=' + data.id);
			}
			if( data.description){
				$( 'p', el).text( data.description);
			}
			if( data.pageTotal || data.pageTotal == 0){
				$( 'span.wiki-page-total', el).text( data.pageTotal);
			}
			if( data.pubdate){
				$( 'span.wiki-pubdate', el).text( data.pubdate);
			}
			if( data.update){
				$( 'span.wiki-update', el).text( data.update);
			}
			if( data.owner){
				$( 'span.wiki-owner', el).text( data.owner);
			}
		}
		function onSettingUpdateHandler( e, _data){
			for(var key in _data){
				if( _data[ key] === false){
					delete data[ key];
				} else {
					data[ key] = _data[ key];
				}
			}
			build( data);
			
			list.trigger( wiki.event.SETTING_UPDATE_EVENT);
		}
		function onEditClick(){
			if( !data.isRocked && !wiki.updating){ // 更新中でない
				location.href = wiki.baseUrl + '?view=wiki&edit=1&wikiId=' + data.id;
			}
		}
		function onSettingClick(){
			if( !wiki.updating){
				wiki.setting.show( el, data);
				el.bind( wiki.event.SETTING_UPDATE_EVENT, onSettingUpdateHandler);
				el.bind( wiki.event.SETTING_CLOSED_EVENT, onSettingClosedHandler);
			}
		}
		function onSettingClosedHandler( e){
			el.unbind( wiki.event.SETTING_UPDATE_EVENT, onSettingUpdateHandler);
			el.unbind( wiki.event.SETTING_CLOSED_EVENT, onSettingClosedHandler);
		}				
		function onDeleteClick(){
			if( !data.isRocked && !wiki.updating) {
				list.trigger(wiki.event.WIKI_DELETE_EVENT, data.id);
			}
		}			
		return	{
			data: data,
			el: el,
			remove: function(){
				editButton.unbind( 'click', onEditClick);
				settingButton.unbind( 'click', onSettingClick);
				deleteButton.unbind( 'click', onDeleteClick);
				
				onSettingClosedHandler( null);
				el.remove();
			}
		}
	}
	

// ---------------------------------------------------
// wiki setting
//	
	wiki.setting = (function(){
		var targetEl;
		var	console = $( $('#wikiSettingTemplate').html());
		var	rockButton = console.find( '#wiki-setting-rock');
		var	shareEditableButton =  console.find( '#wiki-share-editable');
		var	shareButton = console.find( '#wiki-share');
		var	colorButtons = console.find( '#wiki-setting-color span');

		function onRockClick(){
			var	r = rockButton.attr( 'checked'),
				se = shareEditableButton.attr( 'checked'),
				s = shareButton.attr( 'checked');		
			if( r && se){ // ロック＆共有編集可の場合、編集不可に。
				se = false;
				s = true;
			}
			buildSetting( true, r, se, s);
		}
		function onShareEditableClick(){
			var	r = rockButton.attr( 'checked'),
				se = shareEditableButton.attr( 'checked'),
				s = shareButton.attr( 'checked');
			if( r){
				se = false;
			} else if( se && s){
				s = false;
			}
			buildSetting( true, r, se, s);
		}
		function onShareClick(){
			var	r = rockButton.attr( 'checked'),
				se = shareEditableButton.attr( 'checked'),
				s = shareButton.attr( 'checked');
			if( se && s){
				se = false;
			}
			buildSetting( true, r, se, s);
		}
		function buildSetting( update, rocked, shareEditable, share){
			rockButton.attr( 'checked', rocked);
			shareEditableButton.attr( 'checked', shareEditable);
			shareButton.attr( 'checked', share);
			
			if( update){
				targetEl.trigger( wiki.event.SETTING_UPDATE_EVENT, {
					isRocked:		rocked,
					shareEditable:	shareEditable,
					share:			share
				});				
			}
		}
		
		function onColorClick(){
			targetEl.trigger( wiki.event.SETTING_UPDATE_EVENT, { color: $( this).attr( 'class')});
		}
		
		return {
			show: function( _targetEl, data){
				if( !!targetEl){
					targetEl.trigger( wiki.event.SETTING_CLOSED_EVENT);
				}
				targetEl = _targetEl;
				targetEl.find( '.wiki-thumb-control').append( console);
				
				rockButton.click( onRockClick);
				shareEditableButton.click( onShareEditableClick);
				shareButton.click( onShareClick);
				colorButtons.click( onColorClick);
				
				buildSetting( false, !!data.isRocked, !!data.shareEditable, !!data.share);
			},
			hide: function(){
				if( !!targetEl){
					rockButton.unbind( 'click', onRockClick);
					shareEditableButton.unbind( 'click', onShareEditableClick);
					shareButton.unbind( 'click', onShareClick);
					colorButtons.unbind( 'click', onColorClick);
					console.remove();
					
					targetEl.trigger( wiki.event.SETTING_CLOSED_EVENT);
					targetEl = null;
				}
			}
		}
	})();
	
// ---------------------------------------------------
// wiki social
//	
	wiki.social = (function(){
		return {
			sendMsg: function( title, url, body, ajaxButton){
				/*
				var batch = osapi.newBatch();
					.add('activities', osapi.activities.create({ activity: { title: title, url: url } }))
					.add('messages', osapi.messages.send({ userId: '@viewer', message: { recipients: viewer.followerIds, title: title, body: body } }));
					
				batch.execute(function(response) {
					var activities = response.activities,
						messages = response.messages;
					
					if (activities.error) {
						return //oops(activities.error.message);
					}
					if (messages.error) {
						return //oops(messages.error.message);
					}
					
					if ( ajaxButton) {
						ajaxButton.removeClass('ui-state-ajax');
					}

					//location.href = url;
				});
				*/			
			}
		}
	})();
